package com.ynu.znkz.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ynu.znkz.commomutils.R;
import com.ynu.znkz.commomutils.ResultCode;
import com.ynu.znkz.entity.*;
import com.ynu.znkz.entity.vo.QueryPaperVo;
import com.ynu.znkz.entity.vo.TopLevelResearchObj;
import com.ynu.znkz.exception.CustomizeException;
import com.ynu.znkz.service.PaperService;
import com.ynu.znkz.commomutils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/paper")
@CrossOrigin
public class PaperController {

    @Autowired
    private PaperService paperService;

    //获取文献列表信息（带条件分页）
    @PostMapping("/{page}/{size}")
    public R getPaperListPageInfo(@PathVariable(value = "page") Long page, @PathVariable(value = "size") Long size,
                                  @RequestBody(required = false) QueryPaperVo queryPaperVo) {
        System.out.println(page+","+size+","+queryPaperVo);
        //创建page对象
        Page<Paper> pageParam = new Page<>(page, size);

        //调用方法实现条件分页
        paperService.pageQuery(pageParam, queryPaperVo);
        List<Paper> records = pageParam.getRecords();
        long total = pageParam.getTotal();
        return  R.ok().data("total", total).data("rows", records);

    }

    //上传文件
    @PostMapping(value = "/upload")
    public R upload(@RequestPart("file") MultipartFile file) {
        //pdf保存到数据库
        String filename = file.getOriginalFilename();
        String originalFilename = file.getOriginalFilename();

        int dot = filename.lastIndexOf('.');
        if ((dot >-1) && (dot < (filename.length()))) {
            filename =  filename.substring(0, dot);
        }

        String result = paperService.seachPaper(filename);
        //返回no，数据库中没有该论文，可以添加
        if(result =="no"){
            if (Objects.isNull(file) || file.isEmpty()) {
                //判断非空
                return R.error().message("文件为空，请重新上传");
            }
            try {
                byte[] bytes = file.getBytes();
                //要存入本地的地址放到path里面
                Path path = Paths.get( FileUtils.UPLOAD_FOLDER + "/");
                //如果没有files文件夹，则创建
                if (!Files.isWritable(path)) {
                    Files.createDirectories(path);
                }
                FileUtils.getFileByBytes(bytes, FileUtils.UPLOAD_FOLDER, originalFilename);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else
            return R.error().message("数据库中已有该论文");
        return R.ok().message("上传成功");
    }

    //上传文件表单
    @PostMapping("/uploadData")
    public R uploadData(@RequestParam(required = false) String userName,
                        @RequestBody(required = true) Paper paper) {
        if(userName==null){
            return R.error().message("请先登录！");
        }else{
            String result = paperService.addPaper(userName,paper);
            return R.ok().message("上传成功").data("message",result);
        }
    }

    //查询所有分类相关数据
    @GetMapping("/getAllSubjectInfo")
    public R getAllSubjectInfo() {
        //研究方法集合
        List<PaperResearchMethod> researchMethodList = paperService.getAllResearchMethod();
        //研究对象二级分类集合
        List<TopLevelResearchObj> researchObjList = paperService.getAllResearchObj();
        //研究焦点集合
        List<PaperFocus> focusList = paperService.getAllFocus();
        //研究问题集合
        List<PaperResearchProblem> researchProblemList = paperService.getAllResearchProblem();
        //用户集合
        List<User> userList = paperService.getAllUser();
        return R.ok().data("researchObjList", researchObjList)
                .data("researchMethodList", researchMethodList)
                .data("focusList", focusList)
                .data("userList", userList)
                .data("researchProblemList", researchProblemList);
    }

    //文件下载
    @GetMapping(value = "/download/{fileName}", produces = {MediaType.ALL_VALUE})
    public void download(@PathVariable String fileName, HttpServletResponse response) {
        // 以流的形式下载文件。
        try{
            OutputStream os = response.getOutputStream();
            String newFileName = new String(fileName.getBytes("GBK"),"ISO-8859-1");
            InputStream is = Thread.currentThread().getClass().getClassLoader().getResourceAsStream("uploadFile/" + fileName);

            if(is == null) {
                //文件不存在
                throw new CustomizeException(ResultCode.FILE_NOT_EXIST, "文献不存在");
            }
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition","attachment;fileName=" + newFileName+".pdf");
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = is.read(b, 0, b.length)) != -1) {
                os.write(b, 0, len);
            }
            is.close();
            os.close();
        } catch (IOException e) {
            throw new CustomizeException(ResultCode.FAILED_DOWNLOAD, "下载文献失败");
        }
    }

    //根据id删除文件信息
    @DeleteMapping("/{paperId}")
    public R deletePaperInfoByUserName(@PathVariable(value = "paperId") String paperId, @RequestParam(value = "paperName") String paperName) {

        boolean isDelete = paperService.removePaper(paperName);
        if(isDelete) {
            boolean flag = paperService.removeById(paperId);
            if(flag) return R.ok().data("code", ResultCode.SUCCESS);
        }
        //删除文献
        return R.error().message("删除文献信息失败！");
    }

}
